package com.mfnote.util.image;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import com.mfnote.view.R;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;

/**
 * 图片管理类
 * 
 * @author ZHF
 * 
 */
public class ImageManager {

	private Context context;// 上下文对象

	public ImageManager(Context context) {
		this.context = context;
	}

	/** 为图片创建不同的名称用于保存，避免覆盖 **/
	public static String createFileName() {
		String fileName = "";
		Date date = new Date(System.currentTimeMillis()); // 系统当前时间
		SimpleDateFormat dateFormat = new SimpleDateFormat(
				"'IMG'_yyyyMMdd_HHmmss");
		fileName = dateFormat.format(date) + ".jpg";
		return fileName;
	}

	/** 根据图片存放路径获取图片 **/
	public static Bitmap bitmapfromFilePath(String pathName) {
		Bitmap bitmap = null;

		BitmapFactory.Options opts = new BitmapFactory.Options();
	    opts.inJustDecodeBounds = true;  //不占用内存
	    BitmapFactory.decodeFile(pathName, opts); // 生成bitMap的时候会报OOM异常
	    
	    opts.inSampleSize = computeSampleSize(opts, -1, 480*800);     //就可动态计算出图片的inSampleSize。 
	    opts.inJustDecodeBounds = false;//false --- allowing the caller to query the bitmap without having to allocate the memory for its pixels. 
	    try {
	    	bitmap = BitmapFactory.decodeFile(pathName, opts);
	    } catch (OutOfMemoryError e) {
	        e.printStackTrace();
	    }
		// if(!bitmap.isRecycled()) {//通过Bitmap.recycle()方法来释放位图所占的空间，当然前提是位图没有被使用。
		// bitmap.recycle(); //回收图片所占内存
		// System.gc(); //提醒垃圾回收
		// }
		return bitmap;
	}
	
	/**根据原始图片的长度和宽度，即opts.width和opts.height，通过一定的算法，即可得到一个恰当的inSampleSize**/
	public static int computeSampleSize(BitmapFactory.Options options,
	        int minSideLength, int maxNumOfPixels) {
	    int initialSize = computeInitialSampleSize(options, minSideLength,
	            maxNumOfPixels);
	 
	    int roundedSize;
	    if (initialSize <= 8) {
	        roundedSize = 1;
	        while (roundedSize < initialSize) {
	            roundedSize <<= 1;
	        }
	    } else {
	        roundedSize = (initialSize + 7) / 8 * 8;
	    }
	 
	    return roundedSize;
	}

	/**通过一定的算法，即可得到一个恰当的inSampleSize**/
	private static int computeInitialSampleSize(BitmapFactory.Options options,
			int minSideLength, int maxNumOfPixels) {
		double w = options.outWidth;
		double h = options.outHeight;
		int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math
				.sqrt(w * h / maxNumOfPixels));
		int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(
				Math.floor(w / minSideLength), Math.floor(h / minSideLength));
		if (upperBound < lowerBound) {
			// return the larger one when there is no overlapping zone.
			return lowerBound;
		}
		if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
			return 1;
		} else if (minSideLength == -1) {
			return lowerBound;
		} else {
			return upperBound;
		}
	}

	/** 将获取到的图片路径集合切割后保存到集合中 **/
	public ArrayList<String> str2List(String imgsPath) {

		ArrayList<String> list = new ArrayList<String>();

		if (imgsPath != null && !imgsPath.equals("")) {
			String[] tempStr = imgsPath.split("g");
			for (int i = 0; i < tempStr.length; i++) {
				String str = tempStr[i] + "g";
				list.add(str);
			}
		} else {
			return list;
		}
		return list;
	}

	/**判断是否是一张图片**/
	public boolean subImagePathString(String imgPath) {
		boolean flag = false;
		
//		imgPath.substring(0,48);
		if(imgPath.length() == 48) {
			flag = true; //即为一张图片
		}
		return flag;
	}
	
	/** 缩放Bitmap图片 **/
 	public static Bitmap zoomBitmap(Bitmap bitmap, int width, int height) {
		int w = bitmap.getWidth();
		int h = bitmap.getHeight();
		Matrix matrix = new Matrix();
		float scaleWidth = ((float) width / w);
		float scaleHeight = ((float) height / h);
		matrix.postScale(scaleWidth, scaleHeight);// 利用矩阵进行缩放不会造成内存溢出
		Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
		return newbmp;
	}

	/** 切割现有图片重新调整以适应屏幕 */
	public Bitmap[] splitPic(int cols, int rows, Bitmap srcPic, int dstWitdh,
			int dstHeight) {
		final float width = srcPic.getWidth();
		final float height = srcPic.getHeight();

		final int tempWidth = (int) (width / cols);
		final int tempHeight = (int) (height / rows);

		Bitmap[] result = new Bitmap[rows * cols];
		int a = 0;
		for (int i = 0; i < rows; i++) {
			for (int j = 0; j < cols; j++) {
				Bitmap tempBm = Bitmap.createBitmap(srcPic, j * tempWidth, i
						* tempHeight, tempWidth, tempHeight);
				result[a] = zoomBitmap(tempBm, dstWitdh, dstHeight);
				a++;
			}
		}

		return result;
	}

	/**Save image to the SD card**/
	public static void savePhotoToSDCard(String path, String photoName,
			Bitmap photoBitmap) {
		if (android.os.Environment.getExternalStorageState().equals(
				android.os.Environment.MEDIA_MOUNTED)) {
			File dir = new File(path);
			if (!dir.exists()) {
				dir.mkdirs();
			}

			File photoFile = new File(path, photoName); // 在MFNote下面创建图片文件
			FileOutputStream fileOutputStream = null;
			try {
				fileOutputStream = new FileOutputStream(photoFile);
				if (photoBitmap != null) {
					if (photoBitmap.compress(Bitmap.CompressFormat.PNG, 100,
							fileOutputStream)) {
						fileOutputStream.flush();
					}
				}
			} catch (FileNotFoundException e) {
				photoFile.delete();
				e.printStackTrace();
			} catch (IOException e) {
				photoFile.delete();
				e.printStackTrace();
			} finally {
				try {
					fileOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	public static Bitmap syntheticImages(Context context,Bitmap bitmap){
		Bitmap bmpLogo = BitmapFactory.decodeResource(context.getResources(), R.drawable.video);
		Bitmap mBitmap=bitmap;
		//于水印图片合成
		Bitmap drawingBitmap = Bitmap.createBitmap(mBitmap.getWidth(),mBitmap.getHeight(), bmpLogo.getConfig());
		Canvas canvas = new Canvas(drawingBitmap);
	    Paint paint = new Paint();
	    canvas.drawBitmap(bmpLogo, (mBitmap.getWidth()-bmpLogo.getWidth())/2, (mBitmap.getHeight()-bmpLogo.getHeight())/2, paint);
	    paint.setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.DST_OVER));
	    canvas.drawBitmap(mBitmap, 0, 0, paint);
	    return drawingBitmap;
	}
	

}
